package cn.itcast.itcaststore.web.servlet.client;

import cn.itcast.itcaststore.domain.OrderItem;
import cn.itcast.itcaststore.domain.Orders;
import cn.itcast.itcaststore.domain.Products;
import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.serive.OrderService;
import cn.itcast.itcaststore.serive.impl.OrderServiceImpl;
import cn.itcast.itcaststore.utils.IdUtils;
import org.apache.commons.beanutils.BeanUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet( "/createOrder")
public class CreateOrderServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.得到当前用户
        HttpSession session=request.getSession();
        User user=(User) session.getAttribute("user");
        //2.从购物车中获取商品信息
        Map<Products,Integer>cart=(Map<Products, Integer>)session.getAttribute("cart");
        //删除购物车数据
        session.removeAttribute("cart");
        //3.将数据封装到订单对象中
        Orders order=new Orders();
        try {
            BeanUtils.populate(order,request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        order.setId(IdUtils.getUUID());//封装订单id
        order.setUser(user);//封装用户信息到订单
        for (Products p:cart.keySet()){
            OrderItem item=new OrderItem();
            item.setOrder(order);
            item.setBuynum(cart.get(p));
            item.setP(p);
            order.getOrderItems().add(item);
        }
        //调用service中添加订单操作
        OrderService service=new OrderServiceImpl();
        service.addOrder(order);
        response.sendRedirect(request.getContextPath()+"/client/createOrderSuccess.jsp");
    }
}
